import React, { useState } from 'react';
import {
  Form,
  Input,
  Modal,
  message,
  Button,
  Select,
  Popconfirm,
  Descriptions,
} from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import columnsData, { columnsDataType } from './data';
import {
  getContractPageList,
  addContract,
  deleteContract,
  getContractInfo,
} from './service';
import { getContractTemplates } from '@/services/services';
import TableTitle from '../../../components/TableTitle';

export default () => {
  const { TextArea } = Input;
  const { Option } = Select;
  // 控制新增模态框
  const [isConfigurationModal, setIsConfigurationModal] = useState(false);
  // 获取表单
  const [FormRef] = Form.useForm();
  // 存储templateNo，新增需要
  const [isTemplateNoArr, setIsTemplateNoArr] = useState([]);
  // 存储查看record
  const [isViewRecord, setIsViewRecord] = useState({});
  // 控制查看模态框
  const [isViewConfigurationModal, setIsViewConfigurationModal] = useState(
    false,
  );

  /**
   * 以下内容为表格相关
   */

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a
          onClick={() => {
            toViewContractConfig(record);
          }}
        >
          查看
        </a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <Popconfirm
          title="确定删除此条模板？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            toDelContractConfig(record);
          }}
          // onCancel={cancel}
        >
          <a>删除</a>
        </Popconfirm>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();

  /**
   * 以下内容为操作相关
   */

  // 新增配置
  const increaseConfiguration = async () => {
    let resOfTemplateNo = await getContractTemplates({});
    let templateNoArr = resOfTemplateNo?.data?.map((currentValue) => {
      let templateNo = currentValue.serialNo;
      return {
        templateNo,
      };
    });
    console.log('templateNoArr', templateNoArr);
    setIsTemplateNoArr(templateNoArr);
    setIsConfigurationModal(true);
  };

  const confirmAddContract = () => {
    // 获取输入的表单值
    FormRef.validateFields()
      .then(async () => {
        let response = FormRef.getFieldsValue();
        // console.log(response);
        // 新增合约配置接口
        let addRes = await addContract(response);
        console.log('addRes', addRes);
        // 重置输入的表单
        FormRef.resetFields();
        // 刷新proTable
        actionRef.current?.reload();
        setIsConfigurationModal(false);
      })
      .catch(() => {});
  };

  const onCancelConfiguration = () => {
    // 重置输入的表单
    FormRef.resetFields();
    setIsConfigurationModal(false);
  };

  /**
   * 查看合约配置
   */
  const toViewContractConfig = async (record) => {
    let { serialNo } = record;
    let InfoRes = await getContractInfo({ serialNo });
    console.log('InfoRes', InfoRes);
    setIsViewConfigurationModal(true);
    setIsViewRecord(InfoRes.data);
  };

  /**
   * 详情，模板类型对应
   */
  const handleViewRecordOfStatus = () => {
    let { status } = isViewRecord;
    let statusText;
    switch (status) {
      case 0:
        statusText = '未执行';
        break;
      case 1:
        statusText = '执行中';
        break;
      default:
        statusText = '已完成';
    }
    return statusText;
  };

  /**
   * 删除合约配置
   */
  const toDelContractConfig = async (record) => {
    // console.log(record);

    let { serialNo } = record;
    let deleteRes = await deleteContract({ serialNo });
    console.log('deleteRed', deleteRes);
    // 刷新proTable
    actionRef.current?.reload();
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title="合约实例" />}
        scroll={{ x: 900 }}
        bordered
        // 表头
        columns={columns}
        actionRef={actionRef}
        // 请求获取的数据
        request={async (params) => {
          console.log(params);
          let res = await getContractPageList({
            ...params,
          });
          console.log('😒', res);
          const result = {
            data: res.data,
            total: res.pagination.totalSize,
          };
          return result;
        }}
        rowKey="serialNo"
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            onClick={() => {
              increaseConfiguration();
            }}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新增合约
          </Button>,
        ]}
      />
      {/* 新增合约模板模态框 */}
      <Modal
        title="合约实例"
        centered
        visible={isConfigurationModal}
        onOk={confirmAddContract}
        onCancel={onCancelConfiguration}
      >
        <Form
          name="basic"
          form={FormRef}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 14 }}
          initialValues={{ type: 1, status: 0 }}
        >
          <Form.Item
            label="规则名称"
            name="contractName"
            rules={[{ required: true, message: '请输入合约规则名称!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="模版编号"
            name="contractTemplateNo"
            rules={[{ required: true, message: '请选择模版编号!' }]}
          >
            <Select>
              {isTemplateNoArr.map((currentValue) => {
                return (
                  <Option
                    value={currentValue.templateNo}
                    key={currentValue.templateNo}
                  >
                    {currentValue.templateNo}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="合约地址"
            name="contract"
            rules={[{ required: true, message: '请输入合约地址!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="规则描述"
            name="description"
            rules={[{ required: true, message: '请输入规则描述!' }]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
      {/* 查看详情模态框 */}
      <Modal
        title="查看合约配置"
        width={900}
        centered
        visible={isViewConfigurationModal}
        onOk={() => setIsViewConfigurationModal(false)}
        onCancel={() => setIsViewConfigurationModal(false)}
      >
        {/* 详情信息 */}
        <Descriptions title="合约配置">
          <Descriptions.Item label="合约规则编号">
            {isViewRecord.serialNo}
          </Descriptions.Item>
          <Descriptions.Item label="合约模版编号">
            {isViewRecord.contractTemplateNo}
          </Descriptions.Item>
          <Descriptions.Item label="合约规则名称">
            {isViewRecord.contractName}
          </Descriptions.Item>
          <Descriptions.Item label="合约地址">
            {isViewRecord.contract}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {isViewRecord.createTime}
          </Descriptions.Item>
          <Descriptions.Item label="创建者">
            {isViewRecord.createBy}
          </Descriptions.Item>
          <Descriptions.Item label="执行状态">
            {handleViewRecordOfStatus()}
          </Descriptions.Item>
          <Descriptions.Item label="合约规则描述">
            {isViewRecord.description}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
    </div>
  );
};
